﻿using System;
using ESRI.ArcGIS.Geodatabase;

namespace DllShepherd.Core.Esri.Extension
{
    public static class EsriExtensions
    {
        public static int GetFieldIndex(this IRow row, string field)
        {
            return row.Fields.FindField(field);
        }

        public static object GetValue(this IRow row, string field)
        {
            var fieldIndex = row.GetFieldIndex(field);
            if (fieldIndex == -1)
                throw new ArgumentException("Field " + field + " wasn't found in the table.");
            return row.get_Value(fieldIndex);
        }

        public static T GetValue<T>(this IRow row, string field)
        {
            var value = row.GetValue(field);

            T result;
            try
            {
                result = (value == DBNull.Value) ? default(T) : (T)value;
            }
            catch (Exception exp)
            {
                throw new InvalidCastException(String.Format("The value {0} of objectId {1} of field {2} in layer {3} cannot be cast to {4} type.", value, row.OID, field, ((FeatureClass)row.Table).Name, typeof(T)), exp);
            }
            return result;
        }
    }
}
